import React, { Component } from 'react'
import { View, Text } from '@tarojs/components'
import Navbbar from '../../components/Navbbar'
import Searchcard from '../../components/Searchcard'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import requst from '../../utils/http'
import tools from '../../utils/tools'
import './index.less'

export default class SearchDetail extends Component {
  $instance = getCurrentInstance().router.params

  state = {
    detailList:[]
  }
  formatTag = (tag)=>{
    var newarr = tag.split(',').splice(0,2)
    return newarr.join(',')
  }
  gotoDetail = (id)=>{
    Taro.navigateTo({
      url:`../detail/index?id=${id}`
    })
  }
  handleCollect = (info)=>{
    var obj = {...info}
    delete obj.num
    delete obj.gotoDetail
    delete obj.peoplenum
    delete obj.type
    console.log(obj)
    Taro.request({
      url: 'http://127.0.0.1:3007/api/add',
      method: 'POST',
      data:obj,
      success: function (res) {
        console.log(res,11)
      }
    })
    if(tools.tGet('collectList'))
    {
      var arr = tools.tGet('collectList')
      arr.unshift(info)
      tools.tSet('collectList',arr)
    }
    else{
      tools.tSet('collectList',[info])
    }
  }
  componentDidMount(){
    var isClassify = (this.$instance.classid!=undefined)
    var classid = this.$instance.classid
    var start = 0
    var num = 10
    var appkey = '12d96537cc4e185f'
    var keyword = this.$instance.keyword
    console.log(isClassify,1111)
    
    isClassify&&requst(2,'post',`/byclass?appkey=${appkey}&classid=${classid}&start=${start}&num=${num}`,{}).then(res=>{
      this.setState({
        detailList:res.data.result.list
      })
    })
    !isClassify&&requst(2,'post',`/search?appkey=${appkey}&keyword=${keyword}&num=${num}`,{}).then(res=>{
      console.log(1111,res)
      this.setState({
        detailList:res.data.result.list
      })
    })
  }
  render() {
    return (
      <View>
        <Navbbar type={3}></Navbbar>
        <View className='search_result'>
          {this.state.detailList&&this.state.detailList.map(obj=><Searchcard gotoDetail={this.gotoDetail} handleCollect={this.handleCollect} type='s1' pic={obj.pic} name={obj.name} peoplenum={obj.peoplenum} cookingtime={obj.cookingtime} tag={this.formatTag(obj.tag)} key={obj.id} classid={obj.classid} id={obj.id}></Searchcard>)}
        </View>
      </View>
    )
  }
}
